package com.kongt.download;

import com.kongt.Aplication;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Component
@Slf4j
public class DefaultAraumentDownloadConfig implements DownloadConfig {
    final static Pattern compile = Pattern.compile("^-\\w*={1}");
    /**
     * 参数名 下载地址
     */
    private static final String[] _ARGUMENTS = new String[]{"-DdownloadUrl=", "-DthreadC=", "-Dpath="};

    Map<String, String> configMap = new HashMap<String, String>();

    @PostConstruct
    public void loadConfig() throws InterruptedException {
        String[] args = Aplication.get_startArgs();
        if (null != args) {
            for (String arg : args) {
                Matcher matcher = compile.matcher(arg);
                if (!matcher.find()) {
                    throw new InterruptedException("config error，start failed,please check the config！");
                }
                String key = matcher.group();
                log.info("load config:{}", key);
                String value = matcher.replaceAll("");

                configMap.put(key, value);
            }
        }
    }

    @Override
    public int getThreadC() {
        return Integer.parseInt(configMap.get("-DthreadC="));
    }

    @Override
    public String getDownloadUrl() {
        return configMap.get("-DdownloadUrl=");
    }

    @Override
    public String getDownloadPath() {
        return configMap.containsKey("-Dpath=") ? configMap.get("-Dpath=") : System.getProperty("user.home") + "/Downloads";
    }
}
